import {
	asyncRoutes,
	constantRoutes
} from '@/router'
import Layout from '@/layout'
import store from '@/store'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
	if (route.meta && route.meta.roles) {
		return roles.some(role => route.meta.roles.includes(role))
	} else {
		return true
	}
}

// const menuList = [{
//         "create_time": "2018-03-16 11:33:00",
//         "menu_type": "M",
//         "children": [{
//                 "create_time": "2018-03-16 11:33:00",
//                 "menu_type": "C",
//                 "children": [],
//                 "parent_id": 1,
//                 "menu_name": "用户管理",
//                 "icon": "#",
//                 "perms": "system:user:index",
//                 "order_num": 1,
//                 "menu_id": 4,
//                 "url": "/menu/list/index"
//             },
//             {
//                 "create_time": "2018-12-28 10:36:20",
//                 "menu_type": "M",
//                 "children": [{
//                     "create_time": "2018-12-28 10:50:28",
//                     "menu_type": "C",
//                     "parent_id": 73,
//                     "menu_name": "人员通讯录",
//                     "icon": null,
//                     "perms": "system:person:index",
//                     "order_num": 1,
//                     "menu_id": 74,
//                     "url": "/system/book/person"
//                 }],
//                 "parent_id": 1,
//                 "menu_name": "通讯录管理",
//                 "icon": "fa fa-address-book-o",
//                 "perms": null,
//                 "order_num": 1,
//                 "menu_id": 73,
//                 "url": "#"
//             }
//         ],
//         "parent_id": 0,
//         "menu_name": "菜单管理",
//         "icon": "fa fa-adjust",
//         "perms": null,
//         "order_num": 2,
//         "menu_id": 1,
//         "url": "#"
//     },
//     {
//         "create_time": "2018-03-16 11:33:00",
//         "menu_type": "M",
//         "children": [{
//             "create_time": "2018-03-16 11:33:00",
//             "menu_type": "C",
//             "parent_id": 2,
//             "menu_name": "数据监控",
//             "icon": "#",
//             "perms": "monitor:data:view",
//             "order_num": 3,
//             "menu_id": 15,
//             "url": "/system/druid/monitor"
//         }],
//         "parent_id": 0,
//         "menu_name": "系统监控",
//         "icon": "fa fa-video-camera",
//         "perms": null,
//         "order_num": 5,
//         "menu_id": 2,
//         "url": "#"
//     }
// ]

/**
 * 后台查询的菜单数据拼装成路由格式的数据
 * @param routes
 */
function compare(property) {
	return function(a, b) {
		var value1 = a[property];
		var value2 = b[property];
		return value1 - value2;
	}
}
export function generaMenu(routes, data) {
	data.forEach(item => {
		if (item.url === '#') {
			var newArr = []
			data.forEach(childrenItem => {
				if (item.url && childrenItem.url && item.id == childrenItem.parentId) {
					newArr.push({
						sort: childrenItem.sort,
						path: childrenItem.url,
						component: childrenItem.url === '#' ? Layout : (resolve) => require([`@/views${childrenItem.url}/index`],
							resolve),
						children: [],
						name: 'menu_' + childrenItem.id,
						meta: {
							title: childrenItem.name,
							id: childrenItem.id,
							roles: ['admin'],
							icon: childrenItem.icon
						}
					})
				}
			})
			var newArrSort = newArr.sort(compare('sort'))
			const menu = {
				sort: item.sort,
				path: item.id + '_key',
				component: item.url === '#' ? Layout : (resolve) => require([`@/views${item.url}/index`], resolve),
				children: newArrSort,
				name: 'menu_' + item.id,
				meta: {
					title: item.name,
					id: item.id,
					roles: ['admin'],
					icon: item.icon
				}
			}
			routes.push(menu)
		} else if (item.url !== null && item.level === 1) {
			const menu = {
				sort: item.sort,
				path: item.url,
				component: item.url === '#' ? Layout : (resolve) => require([`@/views${item.url}/index`], resolve),
				children: [],
				name: 'menu_' + item.id,
				meta: {
					title: item.name,
					id: item.id,
					roles: ['admin'],
					icon: item.icon
				}
			}
			routes.push(menu)
		}
	})


	routes = routes.sort(compare('sort'))
	// data.forEach(item => {
	//   // alert(JSON.stringify(item))
	//   const menu = {
	//     path: item.url === '#' ? item.id + '_key' : item.url,
	//     component: item.url === '#' ? Layout : (resolve) => require([`@/views${item.url}/index`], resolve),
	//     // hidden: true,
	//     children: [],
	//     name: 'menu_' + item.id,
	//     meta: {
	//       title: item.name, id: item.id, roles: ['admin'], icon: item.icon
	//     }
	//   }
	//   if (item.children) {
	//     generaMenu(menu.children, item.children)
	//   }
	//   routes.push(menu)
	// })
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
	const res = []

	routes.forEach(route => {
		const tmp = { ...route
		}
		if (hasPermission(roles, tmp)) {
			if (tmp.children) {
				tmp.children = filterAsyncRoutes(tmp.children, roles)
			}
			res.push(tmp)
		}
	})

	return res
}

const state = {
	routes: [],
	addRoutes: []
}

const mutations = {
	SET_ROUTES: (state, routes) => {
		state.addRoutes = routes
		state.routes = constantRoutes.concat(routes)
	}
}

const actions = {
	generateRoutes({
		commit
	}, roles) {
		return new Promise(resolve => {
			const loadMenuData = []

			var arr = [{
				path: '*',
				redirect: '/404',
				hidden: true
			}]
			generaMenu(arr, store.state.user.menus)

			let accessedRoutes
			accessedRoutes = arr || []

			commit('SET_ROUTES', accessedRoutes)
			resolve(accessedRoutes)
		})
	}
}

export default {
	namespaced: true,
	state,
	mutations,
	actions
}
